<?php

namespace App\Services\Draw\PoolGroupObject;


use App\Exceptions\BasicException;
use App\Repositories\GiftRepository;
use Illuminate\Support\Collection;

/**
 * 扭蛋抽奖实体
 * @author wrh
 */
class NovicePoolGroup extends PoolGroup
{
//    public $queue_id;
//    public $poolQueueModel;
//
//    /**
//     * @return mixed
//     */
//    public function getQueueId()
//    {
//        return $this->queue_id;
//    }
//
//    /**
//     * @param mixed $queue_id
//     * @return
//     */
//    public function setQueueId($queue_id)
//    {
//        $this->queue_id = $queue_id;
//        return $this;
//    }
//
    public function getNewPoolGroup()
    {
        return $this;
    }
//
//    public function updateExtraData()
//    {
//        return $this->poolQueueModel->updateData(["id" => $this->queue_id], ["status" => 1]);
//        //$this->independent_id
//    }

    public function getPoolPrizeList($user)
    {
        //先通过group查询prize表获取 礼物模板ID  再通过模板ID查询礼物
        $poolPrizeList = $this->poolPrizeModel->getPrizeListWithGift(['pool_id' => $this->pool_id, 'group_id' => $this->group_id], ['gift_template_id', 'count',
            'group_id', 'template_count', 'gift_id']);
        $giftIds       = $poolPrizeList->pluck('gift_id');
        if ($giftIds->isNotEmpty()) {
            $gifts       = (new GiftRepository())->giftsByIdsWithField($giftIds, ['id', 'price']); // 抽中礼物信息
            $giftsWithId = $gifts->keyBy('id');
            foreach ($poolPrizeList as &$template) {
                $template['price'] = $giftsWithId[$template['gift_id']]['price'];
            }
        }
        return $poolPrizeList;
    }

    public function drawPrizes(Collection $poolPrizeList, $poolConfig, $poolGroup, $user, $drawCount)
    {

        $drawPrizes = [];
        if ($drawCount <= 0) {
            return [];
        }
        $poolCount = $poolPrizeList->where('count', '>', 0)->sum('count');

        //奖池礼物不足则全部抽取
        if ($poolCount < $drawCount) {
            //todo 是否要添加补充逻辑
            throw new BasicException(-1, '奖池礼物不充足');
        }

        //队列抽奖
        $sumCount = $poolPrizeList->sum('count');
        //队列总数和抽奖数不一致 报错
        if ($sumCount != $drawCount) {
            throw new BasicException(-1, '抽奖数量异常');
        }

        foreach ($poolPrizeList as $prize) {
            $prizeId                          = $prize->gift_template_id;
            $drawPrizes[$prize->group_id][$prizeId] = $prize->count;
        }

        return $drawPrizes;
    }
}